package cn.changhong.user.util;

import cn.changhong.user.dao.UserMapper;
import cn.changhong.user.model.User;
import cn.changhong.user.model.UserExample;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author zz
 * @Date
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user=new User();
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        List<User> listUser=userMapper.selectByExample(userExample);
        if (listUser.size()==0) {
            throw new UsernameNotFoundException("email not exists");
        }
        user=listUser.get(0);
        if (user.getStatus()==0) {
            throw new UsernameNotFoundException("not active");
        }
        if (user.getStatus()==2) {
            throw new UsernameNotFoundException("frozen user");
        }

        List<GrantedAuthorityImpl> list=new ArrayList();
        list.add(new GrantedAuthorityImpl(user.getRoleId()));

        return new org.springframework.security.core.userdetails.User(user.getEmail(),user.getPassword(),list);
    }
}
